<?php
declare (strict_types=1);

namespace addons\cloud_market\controller\api;

use addons\cloud_market\controller\api\CloudMarketApiController;
use addons\cloud_market\model\CloudMarketAttachment;
use addons\cloud_market\model\CloudMarketAttachmentGroup;
use think\App;
use think\file\UploadedFile;
use think\Request;
use think\Exception;
use hiduoke\services\UploadService;
use hiduoke\services\FormBuilder as Form;
use app\common\services\Attachment as AttachmentService;

/**
 * 附件控制器
 * @package app\controller\adminapi
 * User: liuhongbin
 * Date: 2021-05-26 0:28
 */
class Attachment extends CloudMarketApiController
{
    /**
     * @var AttachmentService
     */
    private $service;

    /**
     * @var CloudMarketAttachment
     */
    protected $model;

    public function initialize()
    {
        parent::initialize();
        $this->service = new AttachmentService();
        $this->model = new CloudMarketAttachment();
        $this->group = new CloudMarketAttachmentGroup();
    }

    public function index()
    {
        return $this->success();
    }

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function list()
    {
        $params = $this->request->buildParams();
        $where = $params['where'];
        if ($where['group_id'] == -1) {
            unset($where['group_id']);
        }
        $where['user_id']  = $this->getUser()['id'];
        $data = $this->model->where($where)->limit($params['size'])->order([ 'id' => 'DESC'])->page($params['page'])->select();
        $count = $this->model->where($where)->count();
        return $this->success($count, $data);
    }


    /**
     * @param string $file
     * @param int $type
     * @param int $uid
     * @param int $group_id
     * @param int $plaid
     * @return array|\think\response\Json
     * @throws Exception
     */
    public function upload($file = '', $type = 0, $user_id = 0, $group_id = 0)
    {
        if (!$file) return $this->error("文件参数不能为空");
        try {
            if (!$user_id) {
                $user_id = $this->userInfo['id'];
            }
            $path = $this->service->getPathByType($type);
            $upload = UploadService::init();
            $res = $upload->path($path)->validate()->save($file);
            if ($res === false) {
                return $this->error("上传失败");
            } else {
                $fileInfo = $upload->getUploadInfo();
                $data = array(
                    "filename"   => $fileInfo['filename'],
                    "name"       => $fileInfo['oldName'],
                    "attachment" => $fileInfo['dir'],
                    "url"        => $fileInfo['url'],
                    "filesize"   => $fileInfo['size'],
                    "filetype"   => $fileInfo['type'],
                    "type"       => $type,
                    "user_id"        => $user_id,
                    "driver"     => $upload->getName(),
                    "group_id"   => $group_id
                );
                $this->model->save($data);
                return $this->success('上传成功', $data);
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }


    /**
     * 显示编辑资源表单页.
     *
     * @param int $id
     * @return \think\Response
     */
    public function edit($id)
    {
        $id = input("id", 0);
        $rule = array();
        $form = Form::createForm("/adminapi/attachment/index/" . $id)->setMethod("PUT");
        $row = $this->model->where(['id' => $id])->findOrEmpty();
        $rule[] = Form::input('name', '名称', $row->name);
//        $rule[] = Form::input('sort', '排序', $row->sort);
        $form->setTitle("编辑")->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * 保存更新的资源
     *
     * @param \think\Request $request
     * @param int $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        $data = $this->model->where(['id' => $id])->find();
        if ($data) {
            $data->save($request->post('formData'));
            return $this->success("编辑成功");
        } else {
            return $this->error("附件不存在");
        }
    }

    /**
     * 移动附件分组
     * @param $ids
     */
    public function move($group_id, $ids)
    {
        $this->model->whereIn("id", $ids)->save(['group_id' => $group_id]);
        return $this->success("移动成功");
    }


    /**
     * 删除指定资源
     *
     * @param int $id
     * @return \think\Response
     */
    public function delete($ids)
    {
        $upload = UploadService::init();
        $delData = $this->model->whereIn("id", $ids)->select();
        foreach ($delData as $key => $val) {
            $upload->delete($val['attachment']);
        }
        $delData->delete();
        return $this->success("删除成功");
    }

    public function down($url='')
    {
        $uid = $this->userInfo['uid'];
        if(!$url) return $this->error('参数错误');
        // 获取图片名
        $mimeType = get_headers($url, true)['Content-Type'] ?? false;
        $originalName = basename($url) ?? false;
        if (!$mimeType || !$originalName) {
            return $this->error('下载失败');
        }
        try {
            $imageData = file_get_contents($url);
            $tempFilePath = tempnam(sys_get_temp_dir(), 'image');
            file_put_contents($tempFilePath, $imageData);
            $uploadedFile = new UploadedFile($tempFilePath, $originalName, $mimeType, 0);
            $path = (new AttachmentService())->getPathByType(1);
            $upload = UploadService::init();
            $res = $upload->path($path)->validate()->save($uploadedFile);
            if ($res === false) {
                return $this->error();
            } else {

                $fileInfo = $upload->getUploadInfo();
                $data = array(
                    "filename"   => $fileInfo['filename'],
                    "name"       => $fileInfo['oldName'],
                    "attachment" => $fileInfo['dir'],
                    "url"        => $fileInfo['url'],
                    "filesize"   => $fileInfo['size'],
                    "filetype"   => $fileInfo['type'],
                    "plaid"      => get_plaid(),
                    "type"       => 1,
                    "uid"        => $uid,
                    "driver"     => $upload->getName(),
                    "group_id"   => 0
                );
                $this->model->save($data);
                return $this->success('上传成功', $data);
            }
        } catch (\Exception $e) {
            return $this->error($e->getMessage());
        }
    }


    /********************************************* 分组 ************************************************/

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function getGroupList()
    {
        $default_group = [
            ['name' => "全部", 'id' => "-1"],
            ['name' => "未分组", 'id' => "0"]
        ];
        $user_id = $this->userInfo['id'];
        $group = $this->group->where([
            'user_id' => $user_id,
        ])
            ->order("weigh",'desc')
            ->select()
            ->toArray();
        $group = array_merge($default_group, $group);
        return $this->success("ok", $group);
    }

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     * @throws \FormBuilder\Exception\FormBuilderException
     */
    public function getGroupForm()
    {
        $rule = array();
        $id = input("id", 0);
        $row = $this->group->where(['id' => $id])->findOrEmpty();
        $form = Form::createForm("/api.attachment/saveGroup")->setMethod("POST");
        $rule[] = Form::input('name', '名称', $row['name']??"新分组")->required();
        $rule[] = Form::input('weigh', '排序', $rou['weigh']??"1");
        if($row->isEmpty()) {
            $title  = '新增';
        }else{
            $title  = '编辑';
        }
        $form->setTitle($title)->setRule($rule);
        return $this->success("", Form::getFormData($form));
    }

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @return \think\response\Json
     */
    public function saveGroup()
    {
        $id = input('id',0);
        $row = $this->group->where(['id' => $id])->findOrEmpty();
        $formData = getFormData();
        $formData['user_id'] = $this->userInfo['id'];
        $row->save($formData);
        return $this->success("新增成功");
    }


//    /**
//     * 显示编辑资源表单页.
//     * @Route("AttachmentGroup/id/edit", method="GET")
//     * @param int $id
//     * @return \think\Response
//     */
//    public function editGroup($id)
//    {
//        $rule = array();
//        $form = Form::createForm("/adminapi/attachment/group/" . $id)->setMethod("put");
//        $row = $this->model->where(['id' => $id])->findOrEmpty();
//        $rule[] = Form::input('name', '名称', $row->name)->required();
//        $rule[] = Form::input('sort', '排序', $row->sort);
//        $form->setTitle("编辑")->setRule($rule);
//        return $this->success("", Form::getFormData($form));
//    }

//    /**
//     * 保存更新的资源
//     * @Route("AttachmentGroup/id", method="PUT")
//     * @param \think\Request $request
//     * @param int $id
//     * @return \think\Response
//     */
//    public function update(Request $request, $id)
//    {
//        $formData = $this->request->post("formData");
//        $row = $this->model->where(['id' => $id])->find();
//        if (!$row) {
//            return $this->error("分组不存在");
//        }
//        $row->save($formData);
//        return $this->success("编辑成功");
//    }

    /**
     * Create by :  刘泓宾<514660094@qq.com>
     * @param $id
     * @return \think\response\Json
     */
    public function deleteGroup($id)
    {
        $this->model->where(['id' => $id])->delete();
        return $this->success("删除成功");
    }
}
